package com.xzuf.communication;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

import org.apache.commons.lang.StringUtils;
import org.jdesktop.swingworker.SwingWorker;

import com.xzuf.plugin.IModulePlugin;
import com.xzuf.pub.GlobalValue;

/**
 *
 * @author xzgf
 * @since 2008-10-9
 * @version 1.0
 */
public class CommunicationBookUI extends JPanel implements IModulePlugin,ActionListener{
	
	private static final String dbUrl = "jdbc:mysql://localhost:3307/addressbook";
	
	private static final String dbDriver = "org.gjt.mm.mysql.Driver";
	
	private static final String dbUser = "root";
	
	private static final String dbPassword = "root";
	
	private static Connection connection = null;
	
	private JTextField tf_queryName = null;
	
	private JButton btn_query = null;
	
	private JButton btn_new = null;
	
	private JButton btn_delete = null;
	
	private JButton btn_modify = null;
	
	private JTable detailTable = null;
	
	private JLabel lb_msg = null;
	
	private void initDbConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		if(connection == null) {
			Properties dbProp = new Properties();
			dbProp.setProperty("user", dbUser);
			dbProp.setProperty("password", dbPassword);
			Class.forName(dbDriver).newInstance();
			connection = DriverManager.getConnection(dbUrl, dbProp);
		}
		
		if(connection != null) {
			System.out.println("database connection success...");
		} else {
			System.out.println("database connection fail...");
		}
	}
	
	public void initComponent() {
		JLabel lb_name = new JLabel("查询名称:");
		tf_queryName = new JTextField();
		tf_queryName.setPreferredSize(new Dimension(120,22));
		btn_query = new JButton("查询");
		btn_query.addActionListener(this);
		btn_query.setPreferredSize(new Dimension(100,22));
		btn_new = new JButton("新增");
		btn_new.addActionListener(this);
		btn_new.setPreferredSize(new Dimension(100,22));
		btn_delete = new JButton("删除");
		btn_delete.addActionListener(this);
		btn_delete.setPreferredSize(new Dimension(100,22));
		btn_modify = new JButton("修改");
		btn_modify.addActionListener(this);
		btn_modify.setPreferredSize(new Dimension(100,22));
		
		JPanel queryPanel = new JPanel();
		queryPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		queryPanel.setBorder(BorderFactory.createEtchedBorder());
		queryPanel.add(lb_name);
		queryPanel.add(tf_queryName);
		queryPanel.add(btn_query);
		queryPanel.add(btn_new);
		queryPanel.add(btn_delete);
		queryPanel.add(btn_modify);
		
		//
		JPanel detailPanel = new JPanel();
		detailPanel.setLayout(new BorderLayout());
		detailPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"联系人明细"));
		detailTable = new JTable();
		detailTable.setModel(new LinkManTableModel());
		detailTable.setRowHeight(22);
		JScrollPane sp_pane = new JScrollPane(detailTable);
		detailPanel.add(sp_pane,BorderLayout.CENTER);
		
		JPanel extendPanel = new JPanel();
		extendPanel.setLayout(new BorderLayout());
		extendPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "扩展信息"));
		lb_msg = new JLabel();
		extendPanel.add(lb_msg,BorderLayout.CENTER);
		
		//
		this.setLayout(new BorderLayout());
		this.add(queryPanel,BorderLayout.NORTH);
		this.add(detailPanel,BorderLayout.CENTER);
		this.add(extendPanel,BorderLayout.SOUTH);
		
	}
	
	private List<LinkerManVO> getAllLinker(String strLinkmanCode) {
		String sql = "";
		if(StringUtils.isEmpty(strLinkmanCode)) {
			sql = "select linkcode,linkname,telphone,mobilephone,corp,adress,job from linkman order by linkcode";
		} else {
			sql = "select linkcode,linkname,telphone,mobilephone,corp,adress,job from linkman where linkcode like '%" + strLinkmanCode + "%' order by linkcode";
		}
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = connection.prepareStatement(sql);
			rs = pstmt.executeQuery();
			List<LinkerManVO> result = new ArrayList<LinkerManVO>();
			LinkerManVO manVO = null;
			while(rs.next()) {
				manVO = new LinkerManVO();
				manVO.setLinkcode(rs.getString(1));
				manVO.setLinkname(rs.getString(2));
				manVO.setTelphone(rs.getString(3));
				manVO.setMobilephone(rs.getString(4));
				manVO.setCorp(rs.getString(5));
				manVO.setAdress(rs.getString(6));
				manVO.setJob(rs.getString(7));
				result.add(manVO);
			}
			return result;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	private void insertNewMan(LinkerManVO vo) {
		String sql = "insert into linkman (linkcode,linkname,telphone,mobilephone,corp,adress,job ) values (?,?,?,?,?,?,?)";
		PreparedStatement pstmt = null;
		try {
			pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, vo.getLinkcode());
			pstmt.setString(2, vo.getLinkname());
			pstmt.setString(3, vo.getTelphone());
			pstmt.setString(4, vo.getMobilephone());
			pstmt.setString(5, vo.getCorp());
			pstmt.setString(6, vo.getAdress());
			pstmt.setString(7, vo.getJob());
			pstmt.executeUpdate();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
			} catch (SQLException e) {
				JOptionPane.showMessageDialog(this, e.getMessage());
				e.printStackTrace();
			}
		}
	}
	
	
	private void deleteLinkMan(LinkerManVO vo) {
		String str = "delete from linkman where linkname=?";
		PreparedStatement pstmt = null;
		
		try {
			pstmt = connection.prepareStatement(str);
			pstmt.setString(1, vo.getLinkname());
			pstmt.executeUpdate();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
			e.printStackTrace();
		}
	}
	
	private JTextField tf_newcode = null;
	
	private JTextField tf_newname = null;
	
	private JTextField tf_telphone = null;
	
	private JTextField tf_mobilephone = null;
	
	private JTextField tf_corp = null;
	
	private JTextField tf_adress = null;
	
	private JTextField tf_job = null;
	
	private JButton btn_save = null;
	
	private JButton btn_cancel = null;
	
	private JDialog dialog = new JDialog(GlobalValue.mainFrame);
	
	private void showNewLinkManDialog() {
		
		
		dialog.setTitle("联系人信息");
		dialog.setModal(true);
		JLabel lb_code = new JLabel("联系人简称");
		tf_newcode = new JTextField();
		tf_newcode.setPreferredSize(new Dimension(200,22));
		JLabel lb_name = new JLabel("联系人名称");
		tf_newname = new JTextField();
		tf_newname.setPreferredSize(new Dimension(200,22));
		JLabel lb_telphone = new JLabel("固话");
		tf_telphone = new JTextField();
		tf_telphone.setPreferredSize(new Dimension(200,22));
		JLabel lb_mobilephone = new JLabel("手机");
		tf_mobilephone = new JTextField();
		tf_mobilephone.setPreferredSize(new Dimension(200,22));
		JLabel lb_corp = new JLabel("公司");
		tf_corp = new JTextField();
		tf_corp.setPreferredSize(new Dimension(200,22));
		JLabel lb_adress = new JLabel("地址");
		tf_adress = new JTextField();
		tf_adress.setPreferredSize(new Dimension(200,22));
		JLabel lb_job = new JLabel("职务");
		tf_job = new JTextField();
		tf_job.setPreferredSize(new Dimension(200,22));
		
		JPanel contentPanel = new JPanel();
		MigLayout layout = new MigLayout();
		contentPanel.setLayout(layout);
		
		contentPanel.add(lb_code,"cell 0 0");
		contentPanel.add(tf_newcode,"cell 1 0");
		contentPanel.add(lb_name,"cell 0 1");
		contentPanel.add(tf_newname,"cell 1 1");
		contentPanel.add(lb_telphone,"cell 0 2");
		contentPanel.add(tf_telphone,"cell 1 2");
		contentPanel.add(lb_mobilephone,"cell 0 3");
		contentPanel.add(tf_mobilephone,"cell 1 3");
		
		contentPanel.add(lb_corp,"cell 0 4");
		contentPanel.add(tf_corp,"cell 1 4");
		contentPanel.add(lb_adress,"cell 0 5");
		contentPanel.add(tf_adress,"cell 1 5");
		contentPanel.add(lb_job,"cell 0 6");
		contentPanel.add(tf_job,"cell 1 6");
		
		btn_save = new JButton("保存");
		btn_save.addActionListener(this);
		btn_cancel = new JButton("取消");
		btn_cancel.addActionListener(this);
		contentPanel.add(btn_save,"cell 0 8");
		contentPanel.add(btn_cancel,"cell 1 8");
		
		dialog.setContentPane(contentPanel);
		dialog.setSize(new Dimension(400,300));
		dialog.setLocationRelativeTo(null);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setVisible(true);
	}
	
	private void onBoSave() {
		LinkerManVO vo = new LinkerManVO();
		vo.setLinkcode(tf_newcode.getText());
		vo.setLinkname(tf_newname.getText());
		vo.setAdress(tf_adress.getText());
		vo.setCorp(tf_corp.getText());
		vo.setJob(tf_job.getText());
		vo.setTelphone(tf_telphone.getText());
		vo.setMobilephone(tf_mobilephone.getText());
		insertNewMan(vo);
		JOptionPane.showMessageDialog(this, "保存成功...");
		dialog.setVisible(false);
	}
	
	private void onBoQuery() {
		GlobalValue.stateLabel.setText("开始查询..");
		String str = null;
		if(StringUtils.isNotEmpty(tf_queryName.getText())) {
			str = tf_queryName.getText().trim();
		}
		LinkManTableModel model = (LinkManTableModel) detailTable.getModel();
		model.clearBodyData();
		LoadDataTask task = new LoadDataTask(str);
		task.execute();
	}
	
	class LoadDataTask extends SwingWorker<List<LinkerManVO>, LinkerManVO> {
		
		private String strQueryName;
		
		private long startTime = 0L;
		
		@Override
		protected List<LinkerManVO> doInBackground() throws Exception {
//			showBusyFrame();
			startTime = System.currentTimeMillis();
			GlobalValue.progressBar.setIndeterminate(true);
			List<LinkerManVO> result = null;
			result = getAllLinker(strQueryName);
			for(int i=0;i<result.size();i++) {
				Thread.sleep(200);
				publish(new LinkerManVO[] {result.get(i)});  //
			}
			
			return result;
		}
		public LoadDataTask(String strQueryName) {
			this.strQueryName = strQueryName;
		}
		
		@Override
		protected void process(List<LinkerManVO> chunks) {
			LinkManTableModel model = (LinkManTableModel) detailTable.getModel();
			if(chunks != null) {
				for(int i=0;i<chunks.size();i++) {
					model.addRow(chunks.get(i));
				}
			}
			long dt = System.currentTimeMillis() - startTime;
			GlobalValue.stateLabel.setText("耗时: " + dt);
		}
		
		@Override
		protected void done() {
			GlobalValue.stateLabel.setText("查询完成..");
			GlobalValue.progressBar.setIndeterminate(false);
		}
	}

	
	private void onBoDelete() {
		
		int row = detailTable.getSelectedRow();
		String strname = String.valueOf(detailTable.getModel().getValueAt(row, 1));
		if(StringUtils.isEmpty(strname)) {
			JOptionPane.showMessageDialog(this, "联系人名称为空..");
			return;
		}
		LinkerManVO vo = new LinkerManVO();
		vo.setLinkname(strname);
		deleteLinkMan(vo);
		JOptionPane.showMessageDialog(this, "删除成功... [" + vo.getLinkname() + "]");
	}

	@Override
	public int getCurrentOpState() {
		return 0;
	}

	@Override
	public void setCurrentOpState(int state) {
	}

	@Override
	public JPanel start() {
		System.out.println("Begin initialize connection...");
		try {
			initDbConnection();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
		} catch (InstantiationException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
		} catch (IllegalAccessException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
		} catch (ClassNotFoundException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
		System.out.println("End initialize connection..");
		initComponent();
		return this;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btn_new) {
			showNewLinkManDialog();
		}
		if(e.getSource() == btn_save) {
			onBoSave();
		}
		if(e.getSource() == btn_cancel) {
			dialog.setVisible(false);
		}
		if(e.getSource() == btn_query) {
			onBoQuery();
		}
		if(e.getSource() == btn_delete) {
			onBoDelete();
		}
	}

	
}
